package de.uhlesoluschns.opensearch.provider;

import org.json.JSONArray;
import org.json.JSONException;

import com.admob.android.ads.AdView;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import de.uhlesoluschns.opensearch.R;
import de.uhlesoluschns.opensearch.OpenSearch.Suggestion;

public class SuggestionsAdapter extends SimpleCursorAdapter {

	private Uri suggestionUri;
	private ContentResolver contentResolver;
	
	private AdView adView;
	
	public SuggestionsAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, int engineId, JSONArray initialSuggestions) {
		super(context, layout, c, from, to);
		contentResolver = context.getContentResolver();
		suggestionUri = Uri.withAppendedPath(Suggestion.CONTENT_URI, "" + engineId);
		
//		adView = (AdView) LayoutInflater.from(context).inflate(R.layout.suggestion_adview, null);
//		System.out.println(adView.getBackgroundColor());
		
		if(initialSuggestions != null) {
//			try {
//				adView.setSearchQuery(initialSuggestions.getString(0).toString());
//			} catch (JSONException e) {}

			changeCursor((new SuggestionsCursor(initialSuggestions)));
		}
	}
	
	
	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		return contentResolver.query(suggestionUri, SuggestionsCursor.COLUMNS, constraint != null ? constraint.toString() : "", null, null);
	}
	
	@Override
	public CharSequence convertToString(Cursor cursor) {
		if(cursor != null) {
			int column = cursor.getColumnIndex(Suggestion.COL_SUGGESTION);
			if(column >= 0) {
				return cursor.getString(column);
			}
		}
		return null;
	}
	
//	@Override
//	public int getCount() {
//		return super.getCount() + 1;
//	}
//	
//	@Override
//	public View getView(int position, View convertView, ViewGroup parent) {
//		if(position == 0) {
//			return adView;
//		} else {
//			return super.getView(position, convertView, parent);
//		}
//	}
//	
//	@Override
//	public void bindView(View view, Context context, Cursor cursor) {
//		if(view == adView) {
//			adView.setSearchQuery(convertToString(cursor).toString());
//			adView.requestFreshAd();
//		} else {
//			super.bindView(view, context, cursor);
//		}
//	}
//	
//	@Override
//	public boolean areAllItemsEnabled() {
//		return false;
//	}
//	
//	@Override
//	public boolean isEnabled(int position) {
//		return position != 0;
//	}
	
}
